/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.common.aspect;


import cn.hutool.core.collection.CollectionUtil;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.CreateCache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.exception.RRException;
import io.renren.common.utils.Constant;
import io.renren.modules.dangan.entity.DaUserLocationEntity;
import io.renren.modules.sys.dao.SysDictDao;
import io.renren.modules.sys.entity.SysDictEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.shiro.ShiroUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static io.renren.common.utils.Constant.SZD;

/**
 * 数据过滤，切面处理类
 *
 * @author Mark sunlightcs@gmail.com
 */
@Aspect
@Component
public class SzdFilterAspect {

    @Pointcut("@annotation(io.renren.common.annotation.SzdFilter)")
    public void dataFilterCut() {

    }

    @CreateCache(name = "szdCache", cacheType = CacheType.LOCAL, localExpire = 3600, localLimit = 3000)
    private Cache<Integer, List<String>> szdCache;

    @Autowired
    private SysDictDao sysDictDao;
    @Before("dataFilterCut()")
    public void dataFilter(JoinPoint point) throws Throwable {
        Object params = point.getArgs()[0];

        if(params != null && params instanceof Map){
            Map map = (Map)params;
            SysUserEntity user = ShiroUtils.getUserEntity();
            List<String> szdList;
            if(user.getUserId() != Constant.SUPER_ADMIN){
                szdList = szdCache.get(user.getUserId().intValue());
            }else{
                List<SysDictEntity> sysDictEntities=
                        sysDictDao.selectList(new QueryWrapper<SysDictEntity>().eq("type",SZD));
                if(CollectionUtil.isNotEmpty(sysDictEntities)){
                    szdList=sysDictEntities.stream()
                            .map(SysDictEntity::getValue).collect(Collectors.toList());
                }else{
                    szdList=new ArrayList<>();
                }
            }
            if(CollectionUtil.isNotEmpty(szdList)){
                map.put(Constant.SQL_SZD_FILTER,szdList);
            }
            return ;
        }
        return;
    }
}
